<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Methods in C#</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="C#, learn C#, .NET, Mono, methods, tutorial, programming language">
<meta name="description" content="This part of the C# tutorial covers methods.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Methods in C#</h1>

<p>
In this part of the tutorial, you will learn about C# methods.
</p>

<p>
In object oriented programming, we work with objects. Objects are
the basic building blocks of a program. Objects consists of data and
methods. Methods change the state of the objects created. They are
the dynamic part of the objects; data is the static part. 
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script>

<p>
A method is a code block containing a series of statements. 
Methods must be declared within a class or a structure. It is
a good programming practice that methods do only one specific 
task. Methods bring modularity to programs. Proper use of
methods bring the following advantages:
</p>

<ul>
<li>Reducing duplication of code</li>
<li>Decomposing complex problems into simpler pieces</li>
<li>Improving clarity of the code</li>
<li>Reuse of code</li>
<li>Information hiding</li>
</ul>

<p>
Basic characteristics of methods are:
</p>


<ul>
  <li>Access level</li>
  <li>Return value type</li>
  <li>Method name</li>
  <li>Method parameters</li>
  <li>Parentheses</li>
  <li>Block of statements</li>
</ul>

<p>
Access level of methods is controlled with access modifiers. They set the visibility
of methods. They determine, who can call the method. Methods may return a value
to the caller. In case our method returns a value, we provide its data type.
If not, we use the <code>void</code> keyword to indicate, that our method
does not return values. Method parameters are surrounded by parentheses, and separated by commas. 
Empty parentheses indicate that the method requires no parameters. The method
block is surrounded with { } characters. The block contains one or more
statements, that are executed, when the method is <b class="keyword">invoked</b>. 
It is legal to have an empty method block. 
</p>

<p>
A <b class="keyword">method signature</b> is a unique identification 
of a method for the C# compiler. The signature consists of a method
name, and the type and kind (value, reference, or output) of each of 
its formal parameters. Method signature does not include the return
type. 
</p>

<h2>Simple example</h2>

<p>
We start with a simple example. 
</p>

<pre class="code">
using System;


public class Base
{
    public void ShowInfo()
    {
        Console.WriteLine("This is Base class");
    }
}

public class CSharpApp
{
    static void Main()
    {
        Base bs = new Base();
        bs.ShowInfo();
    }
}
</pre>

<p>
We have a <code>ShowInfo()</code> method, that prints
the name of its class. 
</p>

<pre class="explanation">
public class Base
{
    public void ShowInfo()
    {
        Console.WriteLine("This is Base class");
    }
}
</pre>

<p>
Each method must be defined inside a class. Or a struct.
It must have a name. In our case the name is ShowInfo. The 
keywords that precede the name of the method are access specifier
and the return type. Parentheses follow the name of the method.
They may contain parameters of the method. Our method does not
take any parameters.
</p>

<pre class="explanation">
static void Main()
{
   ...
}
</pre>

<p>
This is the Main() method. It is the entry point to each 
console or GUI C# application. It must be declared 
<code>static</code>. We will see later why. The return type
for a Main() method may be <code>void</code> or <code>int</code>.
The access specifier for the Main() method is omitted. In such a 
case a default one is used, which is <code>private</code>. It is
not recommended to use <code>public</code> access specifier for 
a Main() method. It is not supposed to be called by any other methods 
in the assemblies. It is only the CLR that should be 
able to call it when the application starts.
</p>

<pre class="explanation">
Base bs = new Base();
bs.ShowInfo();
</pre>

<p>
We create an instance of the Base class. We call the ShowInfo() method
upon the object. We say, that the method is an instance method. Because
it needs the instance to be called. The method is called by specifying 
the object instance, followed by the member access operator, the dot, 
followed by the method name. 
</p>

<h2>Method parameters</h2>

<p>
<b>Parameters</b> A parameter is a value passed to the method.
Methods can take one or more parameters. If methods work with data, we must
pass the data to the methods. We do it by specifying them inside the parentheses.
In the method definition, we must provide a name and type for each parameter.
</p>


<pre class="code">
using System;


public class Addition
{
    public int AddTwoValues(int x, int y)
    {
        return x + y;
    }

    public int AddThreeValues(int x, int y, int z)
    {
        return x + y + z;
    }
}

public class CSharpApp
{
    static void Main()
    {
        Addition a = new Addition();
        int x = a.AddTwoValues(12, 13);
        int y = a.AddThreeValues(12, 13, 14);

        Console.WriteLine(x);
        Console.WriteLine(y);
    }
}
</pre>

<p>
In the above example, we have two methods. One of them
takes two parameters, the other one takes three parameters.
</p>

<pre class="explanation">
public int AddTwoValues(int x, int y)
{
    return x + y;
}
</pre>

<p>
The AddTwoValues() method takes two parameters. These parameters
have <code>int</code> type. The method also returns an integer to the caller. 
We use the <code>return</code> keyword to return a value from the
method.
</p>

<pre class="explanation">
public int AddThreeValues(int x, int y, int z)
{
    return x + y + z;
}
</pre>

<p>
The AddThreeValues() is similar to the previous method. It takes 
three parameters.
</p>

<pre class="explanation">
int x = a.AddTwoValues(12, 13);
</pre>

<p>
We call the AddTwoValues() method of the addition object. It takes two
values. These values are passed to the method. The method returns a value, 
which is assigned to the x variable. 
</p>

<hr class="btm">

<p>
<b>Variable number of arguments</b> A method can take variable number of arguments.
For this we use the <code>params</code> keyword. No additional parameters are 
permitted after the params keyword. Only one <code>params</code> keyword is permitted 
in a method declaration.
</p>


<pre class="code">
using System;


public class CSharpApp
{

    static void Main()
    {
        Sum(1, 2, 3);
        Sum(1, 2, 3, 4, 5);
    }

    static void Sum(params int[] list)
    {
        Console.WriteLine("There are {0} items", list.Length);
      
        int sum = 0;
        foreach (int i in list) 
        {
            sum = sum + i;
        }

        Console.WriteLine("Their sum is {0}", sum);
    }
}
</pre>

<p>
We create a Sum() method, which can take variable number of arguments.
The method will calculate the sum of values passed to the method.
</p>

<pre class="explanation">
Sum(1, 2, 3);
Sum(1, 2, 3, 4, 5);
</pre>

<p>
We call the Sum() method twice. In one case, it takes 3 arguments,
in the second case 5. We call the same method.
</p>

<pre class="explanation">
static void Sum(params int[] list)
{
...
}
</pre>

<p>
The Sum() method can take variable number of integer values. All
values are added to the list array.
</p>

<pre class="explanation">
Console.WriteLine("There are {0} items", list.Length);
</pre>

<p>
We print the length of the list array. 
</p>

<pre class="explanation">
int sum = 0;
foreach (int i in list) 
{
    sum = sum + i;
}
</pre>

<p>
We compute the sum of the values in the list. 
</p>

<pre>
$ ./variableparams.exe 
There are 3 items
Their sum is 6
There are 5 items
Their sum is 15
</pre>

<p>
Output of the example.
</p>


<h2>Anonymous methods</h2>

<p>
Anonymous methods are inline methods that do not have a name.
Anonymous methods reduce the coding overhead by eliminating 
the need to create a separate method. Without anonymous methods
developers often had to create a class just to call one method. 
</p>

<pre class="code">
using System;
using System.Timers;


public class CSharpApp
{
    static void Main()
    {
        Timer timer = new Timer();

        timer.Elapsed += new ElapsedEventHandler(
            delegate(object source, ElapsedEventArgs e)
            {
                Console.WriteLine("Event triggered at {0}", e.SignalTime);
            }
        );

        timer.Interval = 2000;
        timer.Enabled = true;

        Console.ReadLine();
    }
}
</pre>

<p>
We create a timer object and every 2 seconds we call an anonymous
method.
</p>

<pre class="explanation">
Timer timer = new Timer();
</pre>

<p>
A <code>Timer</code> class generates recurring events in an application.
</p>

<pre class="explanation">
timer.Elapsed += new ElapsedEventHandler(
    delegate(object source, ElapsedEventArgs e)
    {
        Console.WriteLine("Event triggered at {0}", e.SignalTime);
    }
);
</pre>

<p>
Here we plug the anonymous method to the <code>Elapsed</code> event.
The <code>delegate</code> keyword is used to denote an anonymous method.
</p>


<h2>Passing arguments by value, by reference</h2>

<p>
C# supports two ways of passing arguments to methods. By value
and by reference. The default passing of arguments is by value.
When we pass arguments by value, the method works only with the 
copies of the values. This may lead to  performance overheads, 
when we work with large amounts of data. 
</p>

<p>
We use the <code>ref</code> keyword to pass a value by reference.
When we pass values by reference, the method receives a reference 
to the actual values. The original values are affected, when modified. 
This way of passing values is more time and space efficient. On the 
other hand, it is more error prone. 
</p>

<p>
Which way of passing arguments should we use? It depends on the situation. 
Say we have a set of data, salaries of employees. If we want to compute 
some statistics of the data, we do not need to modify them. We pass by values. 
If we work with large amounts of data and the speed of computation is critical, 
we pass by reference. If we want to modify the data, e.g. do some reductions 
or raises to the salaries, we might pass by reference. 
</p>

<p>
<b>Passing by values</b> The following example shows how we pass arguments
by values.
</p>


<pre class="code">
using System;


public class CSharpApp
{

    static int a = 4;
    static int b = 7;

    static void Main()
    {
        Console.WriteLine("Outside Swap method");
        Console.WriteLine("a is {0}", a);
        Console.WriteLine("b is {0}", b);

        Swap(a, b);

        Console.WriteLine("Outside Swap method");
        Console.WriteLine("a is {0}", a);
        Console.WriteLine("b is {0}", b);
    }

    static void Swap(int a, int b)
    {
        int temp;
        temp = a;
        a = b;
        b = temp;
        Console.WriteLine("Inside Swap method");
        Console.WriteLine("a is {0}", a);
        Console.WriteLine("b is {0}", b);
    }
}
</pre>

<p>
The Swap() method swaps the numbers between the a, b variables. 
The original variables are not affected. 
</p>

<pre class="explanation">
static int a = 4;
static int b = 7;
</pre>

<p>
At the beginning, these two variables are initiated. The variables
must be declared <code>static</code>, because they are used from 
static methods.
</p>

<pre class="explanation">
Swap(a, b);
</pre>

<p>
We call the Swap() method. The method takes a, b variables as
arguments.  
</p>

<pre class="explanation">
temp = a;
a = b;
b = temp;
</pre>

<p>
Inside the Swap() method, we change the values. Note that the a, b variables are
defined locally. They are valid only inside the Swap() method. 
</p>


<pre>
$ ./swapbyval.exe 
Outside Swap method
a is 4
b is 7
Inside Swap method
a is 7
b is 4
Outside Swap method
a is 4
b is 7
</pre>

<p>
The output shows, that the original variables were not affected. 
</p>

<hr class="btm">

<p>
<b>Passing by reference</b> The next code example passes values 
to the method by reference. The original variables are changed 
inside the Swap() method. Both the method definition and the
method call must use the <code>ref</code> keyword.
</p>

<pre class="code">
using System;


public class CSharpApp
{

    static int a = 4;
    static int b = 7;

    static void Main()
    {
        Console.WriteLine("Outside Swap method");
        Console.WriteLine("a is {0}", a);
        Console.WriteLine("b is {0}", b);

        Swap(ref a, ref b);

        Console.WriteLine("Outside Swap method");
        Console.WriteLine("a is {0}", a);
        Console.WriteLine("b is {0}", b);
    }

    static void Swap(ref int a, ref int b)
    {
        int temp;
        temp = a;
        a = b;
        b = temp;
        Console.WriteLine("Inside Swap method");
        Console.WriteLine("a is {0}", a);
        Console.WriteLine("b is {0}", b);
    }
}
</pre>

<p>
In this example, calling the Swap() method will change the original 
values.
</p>

<pre class="explanation">
Swap(ref a, ref b);
</pre>

<p>
We call the method with two arguments. They are preceded by the 
<code>ref</code> keyword to indicate, that we are passing arguments
by reference.
</p>

<pre class="explanation">
static void Swap(ref int a, ref int b)
{
...
}
</pre>

<p>
Also in the method declaration, we use the <code>ref</code> keyword 
to inform the compiler that we accept references to the parameters, and
not values. 
</p>

<pre>
$ ./swapbyref.exe 
Outside Swap method
a is 4
b is 7
Inside Swap method
a is 7
b is 4
Outside Swap method
a is 7
b is 4
</pre>

<p>
Here we see, that the Swap() method really changed the values of the variables. 
</p>

<hr class="btm">

<p>
<b>The out keyword</b> The <code>out</code> keyword is similar to the 
<code>ref</code> keyword. The difference is that when using the 
<code>ref</code> keyword, the variable must be initialized before it is
being passed. With the <code>out</code> keyword, it may not be initialized.
Both the method definition and the method call must use the 
<code>out</code> keyword.
</p>

<pre class="code">
using System;


public class CSharpApp
{
    static void Main()
    {
        int val;
        SetValue(out val);

        Console.WriteLine(val);
    }

    static void SetValue(out int i)
    {
        i = 12;
    }
}
</pre>

<p>
An example shows the usage of the <code>out</code> keyword.
</p>

<pre class="explanation">
int val;
SetValue(out val);
</pre>

<p>
The val variable is declared, but not initialized. We pass
the variable to the SetValue() method.
</p>

<pre class="explanation">
static void SetValue(out int i)
{
    i = 12;
}
</pre>

<p>
Inside the SetValue() method it is assigned a value, which
is later printed to the console. 
</p>


<h2>Method overloading</h2>

<p>
<b>Method overloading</b> allows the creation of several methods 
with the same name which differ from each other in the type of 
the input.
</p>

<p>
What is method overloading good for? The Qt4 library gives a nice 
example for the usage. The QPainter class has three methods to draw 
a rectangle. Their name is drawRect() and their parameters differ. 
One takes a reference to a floating point rectangle object, another 
takes a reference to an integer rectangle object and the last one 
takes four parameters, x, y, width, height. If the C++ language, 
which is the language in which Qt is developed, didn't have method 
overloading, the creators of the library would have to name the methods 
like drawRectRectF(), drawRectRect(), drawRectXYWH().
The solution with method overloading is more elegant. 
</p>

<pre class="code">
using System;


public class Sum
{
    public int GetSum()
    {
        return 0;
    }

    public int GetSum(int x)
    {
        return x;
    }

    public int GetSum(int x, int y)
    {
        return x + y;
    }
}

public class CSharpApp
{
    public static void Main()
    {
        Sum s = new Sum();

        Console.WriteLine(s.GetSum());
        Console.WriteLine(s.GetSum(20));
        Console.WriteLine(s.GetSum(20, 30));
    }
}
</pre>

<p>
We have three methods called GetSum(). They differ in input parameters.
</p>

<pre class="explanation">
public int GetSum(int x)
{
    return x;
}
</pre>

<p>
This one takes one parameter.
</p>

<pre class="explanation">
Console.WriteLine(s.GetSum());
Console.WriteLine(s.GetSum(20));
Console.WriteLine(s.GetSum(20, 30));
</pre>

<p>
We call all three methods. 
</p>

<pre class="explanation">
$ ./overloading.exe 
0
20
50
</pre>

<p>
And this is what we get, when we run the example.
</p>

<h2>Recursion</h2>

<p>
Recursion, in mathematics and computer science, is a way of 
defining methods in which the method being defined is applied 
within its own definition. In other words, a recursive method 
calls itself to do its job. Recursion is a widely used approach 
to solve many programming tasks. 
</p>

<p>
A typical example is calculation of the factorial.
</p>

<pre class="code">
using System;


public class CSharpApp
{
    static void Main()
    {        
        Console.WriteLine(Factorial(6));
        Console.WriteLine(Factorial(10));
    }

    static int Factorial(int n)
    {
        if (n == 0)
        {
            return 1;
        } else
        {
            return n * Factorial(n-1);
        }
    }
}
</pre>

<p>
In this code example, we calculate the factorial of two
numbers. 
</p>

<pre class="explanation">
return n * Factorial(n-1);
</pre>

<p>
Inside the body of the factorial method, we call the factorial method
with a modified argument. The function calls itself.
</p>

<pre>
$ ./recursion.exe 
720
3628800
</pre>

<p>
These are the results.
</p>


<h2>Method scope</h2>

<p>
<b>Scope</b> A variable declared inside a method has a method scope.
The <b>scope</b> of a name is the region of program text within which it 
is possible to refer to the entity declared by the name without qualification 
of the name. A variable which is declared inside a method has a method
scope. It is also called a local scope. The variable  is valid only in 
this particular method.
</p>

<pre class="code">
using System;


public class Test
{
    int x = 1;

    public void Show()
    {
        Console.WriteLine(this.x);
        Console.WriteLine(x);
    }
}

public class CSharpApp
{
    static void Main()
    {
        Test ts = new Test();
        ts.Show();
    }
}
</pre>

<p>
In the preceding example, we have an x variable defined outside the Show() 
method. The variable has a class scope. It is valid everywhere inside
the definition of the Test class. In other words, between its curly brackets.
</p>

<pre class="explanation">
public void Show()
{
    Console.WriteLine(this.x);
    Console.WriteLine(x);
}
</pre>

<p>
The x variable, also called the x field is an instance variable. And so
it is accessible through the <code>this</code> keyword. It is also valid
inside the Show() method and can be referred by its bare name. Both
statements refer to the same variable.
</p>

<pre>
$ ./methodscope.exe 
1
1
</pre>

<p>
Output.
</p>

<hr class="btm">

<p>
<b>Shadowing</b> A variable defined inside a method has a
local/method scope. If a local variable has the same name
as a class variable, it shadows the class variable. The
class variable is still accessible inside the method by
using the <code>this</code> keyword. 
</p>

<pre class="code">
using System;


public class Test
{
    int x = 1;

    public void Show()
    {
        int x = 3;

        Console.WriteLine(this.x);
        Console.WriteLine(x);
    }
}

public class CSharpApp
{
    static void Main()
    {
        Base bs = new Base();
        bs.Show();
    }
}
</pre>

<p>
In the preceding example, we declare the x variable
outside the Show() method and inside the Show() method.
Both variables have the same identifiers, but they are
not in conflict. Because they live in different scopes.
</p>

<pre class="explanation">
Console.WriteLine(this.x);
Console.WriteLine(x);
</pre>

<p>
The variables are accessed differently. The x variable
defined inside the method, also called the local variable
is simply accessed by its name. The class variable can be
referred by using the <code>this</code> keyword. 
</p>


<pre>
$ ./methodscope2.exe 
1
3
</pre>

<p>
 Output.
</p>


<h2>Static methods &amp; variables</h2>

<p>
<b>Static methods</b> Static methods are called without an instance
of the object. To call a static method, we use the name of the class
and the dot operator. Static methods can only work with static variables.
Static methods are often used to represent data or calculations that do 
not change in response to object state. An example is a math library, 
which contains static methods for various calculations. We use 
the <code>static</code> keyword to declare a static method or a static
variable. When no static modifier is present, the method is said to 
be an instance method. We cannot use the <code>this</code> keyword in
static methods. It can be used in instance methods only.
</p>


<pre class="code">
using System;


public class Basic
{
    static int Id = 2321;

    public static void ShowInfo()
    {
        Console.WriteLine("This is Basic class");
        Console.WriteLine("The Id is: {0}", Id);
    }
}

public class CSharpApp
{
    static void Main()
    {
        Basic.ShowInfo();
    }
}
</pre>

<p>
In our code example, we define a static ShowInfo() method.
</p>

<pre class="explanation">
static int Id = 2321;
</pre>

<p>
A static method can only work with static variables. 
</p>

<pre class="explanation">
public static void ShowInfo()
{
    Console.WriteLine("This is Basic class");
    Console.WriteLine("The Id is: {0}", Id);
}
</pre>

<p>
This is our static ShowInfo() method. It works with a static
Id member. 
</p>

<pre class="explanation">
Basic.ShowInfo();
</pre>

<p>
To invoke a static method, we do not need an object instance. 
We call the method by using the name of the class and the dot
operator. 
</p>

<pre>
$ ./staticmethod.exe 
This is Basic class
The Id is: 2321
</pre>

<p>
Output of the example.
</p>

<hr class="btm">

<p>
<b>Static variable</b> A static variable belongs to the class
and not to the object of the class. C# supports only static class
members. Static method members are not supported in C#. 
</p>

<pre class="code">
using System;

public class CSharpApp
{
    static void Main()
    {
        Console.WriteLine(Math.PI);
    }
}
</pre>

<p>
The Math is a built-in class which provides some methods and members.
One of them is the PI value, which is a static member. It is accessed
using the Math class name and the dot operator.
</p>

<pre>
$ ./static.exe 
3.14159265358979
</pre>

<hr class="btm">

<p>
<b>Static Main() method</b> The Main() method is an entry point to 
the C# console and GUI application. In C#, the Main() method is required
to be static. Before the application starts, no object is created yet.
To invoke non-static methods, we need to have an object instance.
Static methods exist before a class is instantiated so static is applied 
to the main entry point.
</p>


<h2>Hiding methods</h2>

<p>
When a derived class inherits from a base class, it can define methods,
that are already present in the base class. We say, that we 
<b class="keyword">hide</b> the method of the class, that we have derived 
from. To explicitly inform the compiler about our intention to hide a 
method, we use the  <code>new</code> keyword. Without this 
keyword, the compiler issues a warning. 
</p>


<pre class="code">
using System;

public class Base
{
    public void Info()
    {
        Console.WriteLine("This is Base class");
    }
}

public class Derived : Base
{
    public new void Info()
    {    
        base.Info();
        Console.WriteLine("This is Derived class");
    }
}

public class CSharpApp
{
    static void Main()
    {
        Derived d = new Derived();
        d.Info();
    }
}
</pre>

<p>
We have two classes. The Derived and the Base class. The Derived
class inherits from the Base class. Both have a method called Info().
</p>


<pre class="explanation">
public class Derived : Base
{
...
}
</pre>

<p>
The : character is used to inherit from a class. 
</p>

<pre class="explanation">
public new void Info()
{    
    base.Info();
    Console.WriteLine("This is Derived class");
}
</pre>

<p>
This is an implementation of the Info() method in the Derived
class. We use the <code>new</code> keyword to inform
the compiler about hiding a method from the base class. Note, that
we can still reach the original Info() method. With the help of
the <code>base</code> keyword, we invoke the Info()
method of the Base class too. 
</p>

<pre>
$ ./hidingmethods.exe 
This is Base class
This is Derived class
</pre>

<p>
We have invoked both methods. 
</p>


<h2>Overriding methods</h2>

<p>
Now we will introduce two new keywords. The <code>virtual</code>
keyword and the <code>override</code> keyword. They are both method
modifiers. They are used to implement polymorphic behaviour of objects. 
The <code>virtual</code> keyword creates a virtual method. These methods
can be redefined in the derived classes. Later in the derived class
we use the <code>override</code> keyword to redefine the method in question.
If the method in the derived class is preceded with the <code>override</code>
keyword, objects of the derived class will call that method rather than the 
base class method.
</p>


<pre class="code">
using System;

public class Base
{
    public virtual void Info()
    {
        Console.WriteLine("This is Base class");
    }
}

public class Derived : Base
{
    public override void Info()
    {
        Console.WriteLine("This is Derived class");
    }
}

public class CSharpApp
{
    static void Main()
    {
        Base[] objs = {new Base(), new Derived(), new Base(),
                        new Base(), new Base(), new Derived() };

        foreach (Base obj in objs)
        {
            obj.Info();
        }
    }
}
</pre>

<p>
We create an array of the Base and Derived objects. We go
through the array and invoke the Info() method upon all of
them. 
</p>


<pre class="explanation">
public virtual void Info()
{
    Console.WriteLine("This is Base class");
}
</pre>

<p>
This is the virtual method of the Base class. It is expected to 
be overridden in the derived classes. 
</p>

<pre class="explanation">
public override void Info()
{
    Console.WriteLine("This is Derived class");
}
</pre>

<p>
We override the base Info() method in the Derived class. We use
the <code>override</code> keyword. 
</p>

<pre class="explanation">
Base[] objs = {new Base(), new Derived(), new Base(),
                new Base(), new Base(), new Derived() };
</pre>

<p>
Here we create an array of Base and Derived objects. Note that
we used the Base type in our array declaration. This is because a
Derived class can be converted to the Base class, because it inherits
from it. The opposite is not true. The only way to have both objects
in one array is to use a type which is top most in the inheritance hierarchy
for all possible objects. 
</p>

<pre class="explanation">
foreach (Base obj in objs)
{
    obj.Info();
}
</pre>

<p>
We traverse the array and call Info() on all objects in the array. 
</p>

<pre>
$ ./virtualmethods.exe 
This is Base class
This is Derived class
This is Base class
This is Base class
This is Base class
This is Derived class
</pre>

<p>
This is the output. 
</p>

<p>
Now change the <code>override</code> keyword for <code>new</code> keyword. 
Compile the example again and run it.
</p>

<pre>
$ ./virtualmethods.exe 
This is Base class
This is Base class
This is Base class
This is Base class
This is Base class
This is Base class
</pre>

<p>
This time we have a different output. 
</p>


<h2>Sealed methods</h2>

<p>
A sealed method overrides an inherited virtual method with the 
same signature. A sealed method shall also be marked with the 
override modifier. Use of the <code>sealed</code> modifier prevents 
a derived class from further overriding the method. The word 
<b>further</b> is important. First, a method must be virtual. It
must be later overridden. And at this point, it can be sealed. 
</p>


<pre class="code">
using System;

public class A
{
    public virtual void F()
    {
        Console.WriteLine("A.F");
    }

    public virtual void G()
    {
        Console.WriteLine("A.G");
    }
}

public class B : A
{
    public override void F()
    {
        Console.WriteLine("B.F");
    }

    public sealed override void G()
    {
        Console.WriteLine("B.G");
    }
}

public class C : B
{
    public override void F()
    {
        Console.WriteLine("C.F");
    }

    /*public override void G()
    {
        Console.WriteLine("C.G");
    }*/
}


public class CSharpApp
{
    static void Main()
    {
        B b = new B();
        b.F();
        b.G();
        C c = new C();
        c.F();
        c.G();
    }
}
</pre>

<p>
In the preceding example, we seal method G() in class
B. 
</p>


<pre class="explanation">
public sealed override void G()
{
    Console.WriteLine("B.G");
}
</pre>

<p>
Method G() overrides a method with the same name in the
ancestor of the B class. It is also sealed to prevent from
further overriding the method. 
</p>

<pre class="explanation">
/*public override void G()
{
    Console.WriteLine("C.G");
}*/
</pre>

<p>
These lines are commented, because otherwise the code example would not
compile. The Mono compiler would give the following error: 
sealedmethods.cs(36,26): error CS0239: `C.G()': cannot override 
inherited member `B.G()' because it is sealed.
</p>

<pre class="explanation">
c.G();
</pre>

<p>
This line prints "B.G()" to the console. 
</p>

<pre>
$ ./sealedmethods.exe 
B.F
B.G
C.F
B.G
</pre>

<p>
This is the output. 
</p>


<p>
In this part of the C# tutorial, we covered methods.
</p>



<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem">
<a href="..">Contents</a></span> ‡ <span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified October 24, 2010  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>
